package org.bulu.project.web.config;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;
import org.bulu.project.common.constant.SecurityConstants;
import org.bulu.project.system.security.MyPersistentTokenRepository;
import org.bulu.project.system.security.service.SysUserDetailsService;
import org.bulu.project.web.config.property.SecurityProperties;
import org.bulu.project.web.filter.CaptchaValidationFilter;
import org.bulu.project.web.filter.JwtValidationFilter;
import org.bulu.project.web.security.exception.MyAccessDeniedHandler;
import org.bulu.project.web.security.exception.MyAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security 权限配置
 *
 * @author Ray
 * @since 2023/2/17
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final MyAuthenticationEntryPoint authenticationEntryPoint;
    private final MyAccessDeniedHandler accessDeniedHandler;
    private final RedisTemplate<String, Object> redisTemplate;
    private final CodeGenerator codeGenerator;
    private final SecurityProperties securityProperties;


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 配置HTTP安全请求
        http
                // 授权请求配置
                .authorizeHttpRequests(requestMatcherRegistry -> {
                    // 允许所有用户访问登录路径和验证码接口
                    requestMatcherRegistry
                            .antMatchers(SecurityConstants.LOGIN_PATH, "/api/v1/auth/captcha","/api/upload/upload","/api/upload/cover","/admin/*","/api/v1/palspcenter/*","/api/v1/palcenter/*","/image/*").permitAll() // 指定路径允许所有访问
                            .anyRequest().authenticated(); // 其他所有请求需要认证
                })
                // 异常处理配置
                .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> {
                    httpSecurityExceptionHandlingConfigurer
                            .authenticationEntryPoint(authenticationEntryPoint) // 设置认证失败的入口
                            .accessDeniedHandler(accessDeniedHandler); // 设置访问拒绝的处理
                })
                // 会话管理配置
                .sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // 设置为无状态会话
                // CSRF保护配置
                .csrf(AbstractHttpConfigurer::disable) // 禁用CSRF保护
                // 头信息配置
                .headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) // 禁用X-Frame-Options保护
        ;

        // 添加验证码校验过滤器，放置在用户名密码认证过滤器之前
        // CaptchaValidationFilter是自定义的验证码校验过滤器，需要注入Redis模板和验证码生成器
        http.addFilterBefore(new CaptchaValidationFilter(redisTemplate, codeGenerator), UsernamePasswordAuthenticationFilter.class);

        // 添加JWT校验过滤器，放置在用户名密码认证过滤器之前
        // JwtValidationFilter是自定义的JWT令牌校验过滤器，需要注入Redis模板和安全属性中的JWT密钥
        http.addFilterBefore(new JwtValidationFilter(redisTemplate, securityProperties.getJwt().getKey()), UsernamePasswordAuthenticationFilter.class);

        // 构建并返回http安全配置
        return http.build();
    }

    /**
     * 不走过滤器链的放行配置
     */
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> {
            if (CollectionUtil.isNotEmpty(securityProperties.getIgnoreUrls())) {

                //web.ignoring().requestMatchers(securityProperties.getIgnoreUrls().toArray(new String[0]));
                web.ignoring().antMatchers(securityProperties.getIgnoreUrls().toArray(new String[0]));
            }
        };
    }

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * AuthenticationManager 手动注入
     *
     * @param authenticationConfiguration 认证配置
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

}
